package com.dingding.order.core.phonecall.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.dingding.common.core.config.TinetConfig;
import com.dingding.common.core.config.TinetConfig.Tinet_ON_OFF;
import com.dingding.common.core.exception.bussiness.BizExpEnum;
import com.dingding.common.core.exception.bussiness.BussinessException;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.tinet.TinetResponse;
import com.dingding.common.core.util.tinet.TinetUtil;
import com.dingding.order.core.common.IUserOrderDao;
import com.dingding.order.core.phonecall.service.IPhoneCallService;
import com.dingding.order.dto.phonecall.ReqGetPhoneCall;
import com.dingding.order.dto.phonecall.ResGetPhoneCall;
import com.dingding.order.processer.IOrderProcesser;
import com.dingding.order.processer.ProcesserFactory;

/**
 * @Description:获取被拨电话的service
 * @author fengshuonan
 * @date 2016年10月20日 上午9:54:18
 * @version 叮叮搭车
 * @since 2.4
 */
@Component("phoneCallService")
public class PhoneCallServiceImpl implements IPhoneCallService {

	@Resource(name = "processerFactory")
	private ProcesserFactory processerFactory;
	
	@Resource(name = "userOrderCommonDao")
	private IUserOrderDao userOrderDao;

	/**
	 * @Description:获取被拨打的号码
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	public ResGetPhoneCall getPhoneCall(ReqGetPhoneCall reqGetPhoneCall) {

		ResGetPhoneCall resGetPhoneCall = new ResGetPhoneCall();
		
		// 根据订单类型获取相应订单的处理器
		IOrderProcesser orderProcesser = processerFactory.getOrderProcesser(reqGetPhoneCall.getOrderType());

		//获取发起手机号拨打的电话号码
		String tell = orderProcesser.getCallUserTell(reqGetPhoneCall.getOrderId(),
				reqGetPhoneCall.getUserId());
		
		if(ToolUtil.isBlank(tell)){
			throw new BussinessException(BizExpEnum.GET_ZUSER_PHONE_ERROR);
		}
		
		// 获取对方用户的手机号
		String calledPhone = orderProcesser.getCalledUserTell(reqGetPhoneCall.getOrderId(),
				reqGetPhoneCall.getUserId());
		
		if(ToolUtil.isBlank(calledPhone)){
			throw new BussinessException(BizExpEnum.GET_BUSER_PHONE_ERROR);
		}

		//获取是否需要第三方号码的开关
		if(TinetConfig.TINET_ON_OFF == Tinet_ON_OFF.ON){
			resGetPhoneCall.setTeleType(2);//1：正常号码 2：虚拟号码
			TinetResponse res = TinetUtil.setCache(tell, calledPhone);//调用第三方api加入号码拨打的缓存
			if("1".equals(res.getResult())){//如果api调用失败
				throw new BussinessException(BizExpEnum.TINET_ERROR);
			}
			resGetPhoneCall.setTelephone(TinetConfig.TINETPHONE);
		}else{
			resGetPhoneCall.setTeleType(1);//1：正常号码 2：虚拟号码
			resGetPhoneCall.setTelephone(calledPhone);
		}
		
		return resGetPhoneCall;
	}

}
